package database

import (
	"go-sec-code/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"regexp"
	"time"
)

type GormUser struct {
}

func NewGormUser() *GormUser {
	return &GormUser{}
}

func (*GormUser) GetDB() *gorm.DB {
	dsn := "root:111111@tcp(127.0.0.1:3306)/go_sec_code?charset=utf8mb4&parseTime=True&loc=Local"
	logger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略记录未找到错误
			Colorful:                  false,       // 彩色打印
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger})
	if err != nil {
		panic("failed to connect database")
	}

	return db
}

func isValidField(field string) bool {
	var validFields = []string{"id", "name", "age", "sex"} // 可接受的字段名白名单
	for _, validField := range validFields {
		if validField == field {
			return true
		}
	}
	return false
}

func isLegal(text string) bool {
	regex := "^[0-9a-zA-Z]*$"
	matched, _ := regexp.MatchString(regex, text)
	return matched
}

func (*GormUser) SelectListByName(db *gorm.DB, name string, field string) []model.User {
	//if (!isValidField(field)) {
	//	return nil
	//}
	//if !isLegal(field) {
	//	return nil
	//}

	// 自动迁移模式
	db.AutoMigrate(&model.User{})

	var users []model.User
	//db.Table("user").Unscoped().Where("name = '" + name + "'").Find(&users)
	db.Table("user").Unscoped().Where("name = ?", name).Order(field).Find(&users)
	//db.Table("user").Unscoped().Where("name like '%" + name + "%'").Find(&users)	//存在SQL注入
	//db.Table("user").Unscoped().Where("name like '%?%'", name).Find(&users)
	//db.Table("user").Unscoped().Group(field).Find(&users)
	return users
}

func (*GormUser) SelectLikeByName(db *gorm.DB, name string) []model.User {
	// 自动迁移模式
	db.AutoMigrate(&model.User{})

	var users []model.User
	//db.Table("user").Unscoped().Where("name like " + "'%" + name + "%'").Find(&users)
	db.Table("user").Unscoped().Where("name like ?", "%" + name + "%").Find(&users)
	return users
}

func (*GormUser) SelectPage(db *gorm.DB, limit int, offset int) []model.User {
	// 自动迁移模式
	db.AutoMigrate(&model.User{})

	var users []model.User
	db.Table("user").Unscoped().Limit(limit).Offset(offset).Find(&users)
	return users
}

func (*GormUser) SelectIn(db *gorm.DB, ids []int) []model.User {
	// 自动迁移模式
	db.AutoMigrate(&model.User{})

	var users []model.User
	db.Table("user").Unscoped().Where("id in ?", ids).Find(&users)
	return users
}
